package com.eb.buybuybuy.mapper;

import com.eb.buybuybuy.annotation.Component;
import com.eb.buybuybuy.bean.Cart;
import com.eb.buybuybuy.util.MysqlUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@Component
public class CartMapper {
    public List<Cart> getByUserId(Integer userId) throws SQLException, ReflectiveOperationException {
        return MysqlUtil.query("select * from cart where userId = ?", Cart.class, userId);
    }

    public void increase(Integer userId, Integer goodsId) throws Exception {
        List<Cart> list = MysqlUtil.query("select * from cart where userId = ? and goodsId = ?", Cart.class, userId, goodsId);
        if (list.isEmpty()) {
            MysqlUtil.update("insert into cart(userId, goodsId, number) values(?, ?, 1)", userId, goodsId);
        } else {
            MysqlUtil.update("update cart set number = number+1 where userId = ? and goodsId = ?", userId, goodsId);
        }
    }

    public void decrease(Integer userId, Integer goodsId) throws Exception {
        MysqlUtil.update("update cart set number = number-1 where userId = ? and goodsId = ?", userId, goodsId);
        List<Cart> list = MysqlUtil.query("select * from cart where userId = ? and goodsId = ?", Cart.class, userId, goodsId);
        if (list.get(0).getNumber() == 0) {
            MysqlUtil.update("delete from cart where id = ?", list.get(0).getId());
        }
    }

    public void deleteByUserId(Integer userId) throws SQLException {
        MysqlUtil.update("delete from cart where userId = ?", userId);
    }
}
